//
//  XJYNetApiClient.m
//  高仿萝卜书摘
//
//  Created by 谢俊逸 on 2016/11/27.
//  Copyright © 2016年 谢俊逸. All rights reserved.
//

#import "XJYNetApiClient.h"
#import "XJYHeader.h"
#import <AVOSCloud/AVOSCloud.h>
#import <AVOSCloudIM.h>
#import <LeanCloudSocial/AVOSCloudSNS.h>

@implementation XJYNetApiClient
static XJYNetApiClient *_sharedClient = nil;

+ (XJYNetApiClient *)shareXJYNetClient{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedClient = [[XJYNetApiClient alloc]init];
    });
    return _sharedClient;
}
- (void)registerUser:(NSDictionary *)userInfo{

    AVUser *user = [AVUser user];// 新建 AVUser 对象实例
    user.username = userInfo[@"name"];// 设置用户名
    user.password = userInfo[@"password"];// 设置密码
    //user.email = @"tom@leancloud.cn";// 设置邮箱
    
        [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                
                NSLog(@"注册成功");
                //回到主线程
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter]postNotification:[NSNotification notificationWithName:@"registerSuccessful" object:nil]];
                    // 注册成功
                });
                
            } else {
                NSLog(@"注册失败");
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter]postNotification:[NSNotification notificationWithName:@"registerFailed" object:nil]];
                    // 注册成功
                });
            }
        }];

}

- (void)loginWithLoginPath:(NSString*)path Params:(NSDictionary *)params andBlock:(void (^)(id data, NSError *error))block{
    
    NSString *username = params[@"name"];
    NSString *password = params[@"password"];
    NSLog(@"username%@ password%@",username,password);
    if (username && password) {
        // LeanCloud - 登录
        // https://leancloud.cn/docs/leanstorage_guide-objc.html#登录
        [AVUser logInWithUsernameInBackground:username password:password block:^(AVUser *user, NSError *error) {
            if (!error) {
                NSDictionary *dataLoginList = @{
                                                @"name":username,
                                                @"email":@"",
                                                @"password":password
                                                };
                block(dataLoginList,error);
                [[NSNotificationCenter defaultCenter]postNotification:[NSNotification notificationWithName:@"loginSuccessful" object:nil]];
            } else {
                [[NSNotificationCenter defaultCenter]postNotification:[NSNotification notificationWithName:@"loginFailed" object:nil]];
            }
        }];
    }
}
#pragma mark AVOS

- (void)setupAVOSWithAppId:(NSString *)appId clientKey:(NSString *)clientKey{
    [AVOSCloud setApplicationId:appId clientKey:clientKey];
//    [AVIMClient setUserOptions:@{
//                                 AVIMUserOptionUseUnread: @(YES)
//                                 }];
}


#pragma mark third party login

- (void)setupThirdPartyLogin{
    [AVOSCloudSNS setupPlatform:AVOSCloudSNSSinaWeibo withAppKey:@"2548122881" andAppSecret:@"ba37a6eb3018590b0d75da733c4998f8" andRedirectURI:@"http://wanpaiapp.com/oauth/callback/sina"];
    [AVOSCloudSNS setupPlatform:AVOSCloudSNSQQ withAppKey:@"100512940" andAppSecret:@"afbfdff94b95a2fb8fe58a8e24c4ba5f" andRedirectURI:nil];
    [AVOSCloudSNS setupPlatform:AVOSCloudSNSWeiXin withAppKey:@"wxa3eacc1c86a717bc" andAppSecret:@"b5bf245970b2a451fb8cebf8a6dff0c1" andRedirectURI:nil];
}
- (void)weixinLogin{
    if ([AVOSCloudSNS isAppInstalledForType:AVOSCloudSNSWeiXin]) {
        // 请到真机测试
        [AVOSCloudSNS loginWithCallback:^(id object, NSError *error) {
            //        {
            //            "access_token" = "OezXcEiiBSKSxW0eoylIeN_WWsgxroiydYCNnIX5hyDjK3CwA1hc2bvS1oaaaYqwpP7_vb7nhWadkCXGQukQ0hVjCPvWDHjGqSAF0utf2xvXG5coBh2RZViBKxd0POkMDYu0vNLQoBOTfl9yDzzLJQ";
            //            avatar = "http://wx.qlogo.cn/mmopen/3Qx7ibib84ibZMVgJAaEAN7HW8Kyc3s0hLTKcuSlzSJibG8Mbr4g3PsApj8G1u5XxLq9Dnp7XiafxL9h4RSCUIbX39l6lc90Kyzcx/0";
            //            "expires_at" = "2015-07-30 08:38:24 +0000";
            //            id = oazTlwQwmWLyzz7wxnAXDsSZUjcM;
            //            platform = 3;
            //            "raw-user" =     {
            //                city = "";
            //                country = CN;
            //                headimgurl = "http://wx.qlogo.cn/mmopen/3Qx7ibib84ibZMVgJAaEAN7HW8Kyc3s0hLTKcuSlzSJibG8Mbr4g3PsApj8G1u5XxLq9Dnp7XiafxL9h4RSCUIbX39l6lc90Kyzcx/0";
            //                language = "zh_CN";
            //                nickname = "\U674e\U667a\U7ef4";
            //                openid = oazTlwQwmWLyzz7wxnAXDsSZUjcM;
            //                privilege =         (
            //                );
            //                province = Beijing;
            //                sex = 1;
            //                unionid = ox7NLs813rA9sP6QPbadkulxgHn8;
            //            };
            //            username = "\U674e\U667a\U7ef4";
            //        }
            
            NSLog(@"object : %@ error:%@", object, error);
            if ([self filterError:error]) {
                [AVUser loginWithAuthData:object platform:AVOSCloudSNSPlatformWeiXin block:^(AVUser *user, NSError *error) {
                    [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"loginSuccessful" object:nil]];
                }];
            }
        } toPlatform:AVOSCloudSNSWeiXin];
    } else {
        [self alert:@"没有安装微信，暂不能登录"];
    }

    
}

- (void)qqLogin{
    // 如果安装了QQ，则跳转至应用，否则跳转至网页
    [AVOSCloudSNS loginWithCallback:^(id object, NSError *error) {
        if (error) {
            NSLog(@"failed to get authentication from weibo. error: %@", error.description);
        } else {
            [AVUser loginWithAuthData:object platform:AVOSCloudSNSPlatformQQ block:^(AVUser *user, NSError *error) {
                if ([self filterError:error]) {
                    [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"loginSuccessful" object:nil]];
                }
            }];
        }
    } toPlatform:AVOSCloudSNSQQ];
}

- (void)weiboLogin{
    // 如果安装了微博，直接跳转到微博应用，否则跳转至网页登录
    [AVOSCloudSNS loginWithCallback:^(id object, NSError *error) {
        if (error) {
            NSLog(@"failed to get authentication from weibo. error: %@", error.description);
        } else {
            [AVUser loginWithAuthData:object platform:AVOSCloudSNSPlatformWeiBo block:^(AVUser *user, NSError *error) {
                if ([self filterError:error]) {
                    [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"loginSuccessful" object:nil]];
                }
            }];
        }
    } toPlatform:AVOSCloudSNSSinaWeibo];
}

- (void)alert:(NSString *)message {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
    [alert show];
}
- (BOOL)filterError:(NSError *)error {
    if (error) {
        [self alert:[error localizedDescription]];
        return NO;
    }
    return YES;
}

@end
